/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
import React, { Component } from 'react';
import { Table, Form, Card, Tabs, Select, DatePicker } from 'antd';
import '@/assets/css/settings';
import * as Utils from '../../utils_yyr/action';
import BasicForm from '../../components_yyr/common/basicFormbaobiao';
import Echarts from 'echarts-for-react';
// import 'echarts-gl';
import { euqApplicationName_gl, lotAuth, lotAuth2 } from '../../config';

var date = new Date();
let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
let year = date.getFullYear()
let todayEnd = `${year}-${month}-${day} 23:59:59`
let todayStart = `${year}-${month}-01 00:00:00`
let lastMonth = date.getMonth() ? `0${date.getMonth()}` : date.getMonth()
let lastMonthStart = `${year}-${lastMonth}-01 00:00:00`
let thisYearStart = `${year}-01-01`
let thisYearEnd = `${year}-${month}-01`
console.log(thisYearStart)
console.log(thisYearEnd)
const { TabPane } = Tabs;
const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker
class departmentAnalyse extends Component {

    state = {
        loading: false, //加载中...
        dataSource: [], //数据源
        drawerVisible: false, //新增修改抽屉的显示与隐藏
        chooseData: {}, //用checkbox选择好的数据
        total: 0, //总数据量
        formValues: {
            startTime: thisYearStart,
            endTime: thisYearEnd,
        },
        weekList: [],
        value: '1',
        //  activeKey:'top',
        activeKey: 'top',
        panes: [],
        newTabIndex: 0,
        equipmentTypeChart: [],
        thisMonth: [], lastMonth: [], last90Day: [], dateString: [], EquTypeList: [], DepartmentList: [],
        loadingRecord: false,
        recordTable: [],
        total1: 0,
        formValues1: {
            pageNum: 1,
            pageSize: 10,
        },
        columns: [
            // { title: '序号', width: 100, dataIndex: 'id' },
            {
                title: '详细', dataIndex: 'notScanCount', render: (text, record) => {
                    return <a onClick={() => { this.onRowClick(record) }}>详细</a>
                }, width: 100,align:'center',
            },
            { title: '设备编码', dataIndex: 'equCode', width: 150,align:'center', },
            { title: '设备名称', dataIndex: 'equName', width: 100,align:'center', },
        ]
    };
    constructor(props) {
        super(props);
        // console.log(props);
    }
    componentDidMount() {
        this.getDate()
        this.fetch({
            startTime: thisYearStart,
            endTime: thisYearEnd,
        });
        this.findEquTypePageList()
        this.queryTreeDepartment()
    }
    //初始化加载数据
    fetch = (data) => {
        let option1 = this.option1
        console.log(data)
        let columns = []
        columns[0] = this.state.columns[0]
        columns[1] = this.state.columns[1]
        columns[2] = this.state.columns[2]
        let str = ''
        for (var key in data) {
            if (data[key] || data[key] == 0) {
                str += `&${key}=${data[key]}`
            }
        }
        this.setState({ loading: true, formValues: data })
        this.get(`${euqApplicationName_gl}/maintenance/findMaintenanceTable?${str}`).then(res => {
            let arr = res.data
            this.setState({
                loading: false,
                dataSource: arr,
                total: res.total,
            });
            this.findChart(arr[0] ? arr[0] : {})
        })
        this.get(`${euqApplicationName_gl}/maintenance/findYearMonth?${str}`).then(res1 => {
            let arr = res1.data
            for (let item of arr) {
                columns.push({
                    title: item, width: 130,align:'center',
                    children: [
                        {
                            title: '维修', width: 65,
                            dataIndex: `${item}_wxCount`,
                            render: (text, record, index) => {
                                let month = item
                                let span;
                                for (let lie of record.detailsList) {
                                    if (month == lie.yearMonth && lie.wxCount) {
                                        span = <span style={{ color: 'red', fontWeight: 700 }}>{lie.wxCount}</span>
                                    }
                                }
                                return span ? span : ''
                            },align:'center',
                        },
                        {
                            title: '保养', width: 65,
                            dataIndex: `${item}_byCount`,
                            render: (text, record, index) => {
                                let month = item
                                let aaa;
                                for (let lie of record.detailsList) {
                                    if (month == lie.yearMonth && lie.byCount) {
                                        aaa = <span style={{ color: 'red', fontWeight: 700 }}>{lie.byCount}</span>
                                    }
                                }
                                return aaa ? aaa : ''
                            },align:'center',
                        },
                    ],
                })
            }
            console.log(columns)
            this.setState({ equipmentTypeChart: arr, columns }, () => {
                console.log(this.state.columns)
                this.echartRef1.getEchartsInstance().setOption(option1, true);
            })
        })

    }
    findChart = (record) => {
        console.log(record)
        let option1 = this.option1
        let data = { ...this.state.formValues }
        data.equName = null
        data.equCode = record.equCode ? record.equCode : 'sb'
        console.log(data)
        let str = ''
        for (var key in data) {
            if (data[key] || data[key] == 0) {
                str += `&${key}=${data[key]}`
            }
        }
        this.get(`${euqApplicationName_gl}/maintenance/findMaintenanceChart?${str}`).then(res1 => {
            let arr = res1.data
            console.log(arr)
            option1.dataset.source = arr
            this.setState({ equipmentTypeChart: arr }, () => {
                this.echartRef1.getEchartsInstance().setOption(option1, true);
            })
        })
    }
    findEquTypePageList = () => {
        this.get(`${euqApplicationName_gl}/parameter_setting_equipmentType/findEquTypePageList`).then(res => {
            this.setState({
                EquTypeList: res.data
            });
        })
    }
    queryTreeDepartment = () => {
        // this.get(`${lotAuth}/department/queryTreeDepartment`).then(res => {
        this.get(`${lotAuth2}/department/queryTreeDepartment`).then(res => {
            this.setState({
                DepartmentList: res.data
            });
        })
    }
    getDate = () => {
        var date = new Date();
        let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
        let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
        let year = date.getFullYear()
        let todayEnd = `${year}-${month}-${day} 23:59:59`
        let todayStart = `${year}-${month}-01 00:00:00`
        let thisMonth = [todayStart, todayEnd]
        let lastMonth = this.getLastMonth()
        let last90Day = [this.getLast90Day(), todayEnd]
        this.setState({
            thisMonth, lastMonth, last90Day
        })
        // console.log(todayEnd,todayStart)
        // var dataList = [];
        // for (var i = 0; i < 3; i++) {
        //     var newDate = new Date(date);
        //     newDate.setMonth(date.getMonth() - i);
        //     dataList.unshift(`${newDate.getFullYear()}-${(newDate.getMonth() + 1).toString().padStart(2, '0')}`);
        // }
        // console.log(dataList)
        // console.log(this.getLastMonth())
        // console.log([this.getLast90Day(),todayEnd])
    }
    getLastMonth = () => {//获取上个月日期第一天
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
        if (month == 0) {
            year = year - 1;
            month = 12;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
        return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
    }
    /**
     * 获取上个月月底日期
     */
    getLast90Day = () => {
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
        if (month == 0) {
            month = 12;
            year = year - 1;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
        return yyyyMMdd;
    }

    onChangeTabs = activeKey => {
        console.log(activeKey)
        this.setState({ activeKey });
    };

    onEdit = (targetKey, action) => {
        this[action](targetKey);
    };

    //表单查询
    filterSubmit = values => {
        console.log(values)
        values.startTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDateYYYYMM(values.startTime_endTime[0]) + '-01' : ''
        values.endTime = values.startTime_endTime && values.startTime_endTime.length === 2 ? Utils.getDateYYYYMM(values.startTime_endTime[1]) + '-01' : ''
        delete values['startTime_endTime']
        let data = { ...this.state.formValues, ...values }
        console.log(data)
        this.fetch(data);
    };
    //头部关键字查询部分
    formList = () => {
        const { EquTypeList, formValues, DepartmentList } = this.state;
        const formList = [
            { type: "TIMEFRAMEMONTH", label: "时间", field: "startTime_endTime", allowClear: true, initialValue: [formValues.startTime, formValues.endTime], required: true },
            { type: 'TREESELECT', label: '部门', field: 'deptId', name: 'name', valueField: 'id', allowClear: true, list: DepartmentList },
            { type: 'TREESELECT', label: '类型', field: 'equTypeId', name: 'name', valueField: 'id', allowClear: true, list: EquTypeList },
            { type: 'INPUT', label: '设备', field: 'equName', allowClear: true ,placeholder:'输入设备名称或设备编号'},

        ];
        return formList;
    };
    jump = (record) => {
        this.setState({
            drawerVisible: true
        })
        record.pageNum = 1
        record.pageSize = 10
        this.findInspectionRecordTable(record)
    }
    closeModal = () => {
        this.setState({
            drawerVisible: false
        })
    }
    getXianTiOption = () => {
        var colors = ['#fc944f', '#7fd1ff'];
        let option = {
            color: colors,
            title:{
                text:'导出图片',
                show:false
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['维修', '保养'],
                x: '80%',
                y: '10px',
            },
            grid: {
                left: '2%',
                right: '5%',
                // bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            dataset: {
                dimensions: ['yearMonth', 'wxCount', 'byCount'],
                source: []
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisTick: {
                    alignWithLabel: true
                },
                // data: []
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '维修',
                    type: 'line',
                    label: {
                        show: true,
                    },
                },
                {
                    name: '保养',
                    symbolSize: 20,
                    label: {
                        show: true,
                    },
                    type: 'scatter'
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    show: true,
                    xAxisIndex: [0],
                    // 缩放的开始位置的百分比，0 - 100
                    start: 1,
                    // 缩放的结束位置的百分比，0 - 100
                    end: 100,
                    // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // startValue?: number,
                    // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // endValue?: number
                }
            ]
        };
        this.option1 = option
        return option;
    };
    onRowClick = (record) => {
        this.findChart(record)
    }
    download = () => {
        var canvas = document.getElementsByTagName("canvas")
        if (canvas && canvas.length > 0) {
          // 创建标签
          var oA = document.createElement("a")
          // 设置下载名称
          oA.download = "Echarts图表" + ".png"
          // 设置地址以及文件类型
          oA.href = canvas[0].toDataURL("image/png")
          document.body.appendChild(oA)
          // 触发下载事件
          oA.click()
          // 移除元素
          oA.remove()
        }
      }
    render() {
        const { dataSource, loading, total, formValues, columns } = this.state;
        return (
            <div className="shadow-radius">
                <Tabs hideAdd
                    onChange={this.onChangeTabs}
                    activeKey={this.state.activeKey}
                    type="editable-card"
                    onEdit={this.onEdit}>
                    <TabPane tab="维保对比分析" key="top" closable={false}>
                        <Card>
                            <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                        </Card>
                        <div>
                            <Tabs defaultActiveKey="1" >
                                <TabPane tab="维保次数趋势" key="1">
                                    {/* <Button onClick={()=>{this.download()}}>下载</Button> */}
                                    <div style={{ display: 'flex' }} id="scee">
                                        <Echarts
                                            option={this.getXianTiOption()}
                                            style={{ width: '100%', height: '460px' }}
                                            ref={(e) => { this.echartRef1 = e; }}
                                        />
                                    </div>
                                    <div>
                                        <Table columns={columns} rowKey={(record, index) => record.equCode} dataSource={dataSource} pagination={false} loading={loading} onRowClick={(record) => { this.onRowClick(record) }} scroll={{ x: 'calc(700px + 50%)'}}  bordered={true}/>
                                        {/* <Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} /> */}
                                    </div>
                                </TabPane>
                            </Tabs>
                        </div>
                    </TabPane>
                </Tabs>
            </div>
        );
    }
}
export default Form.create()(departmentAnalyse);
